package com.study.mybatis.executor.resultset.defaults;

import com.study.mybatis.executor.resultset.ResultSetHandler;
import com.study.mybatis.mapping.MappedStatement;
import com.study.mybatis.session.Configuration;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yuantongqin
 * 2021/8/2
 **/
public class DefaultResultSetHandler implements ResultSetHandler {

    protected Configuration configuration;
    private MappedStatement mappedStatement;

    public DefaultResultSetHandler( MappedStatement mappedStatement) {
        this.mappedStatement = mappedStatement;
    }

    @Override
    public <E> List<E> handleResultSets(Statement stmt) throws SQLException {

        List<E> result = new ArrayList<>();
        try {
            ResultSet resultSet = stmt.getResultSet();

            while (resultSet.next()) {
                // 通过反射实例化返回类
                Class<?> entityClass = null;
                entityClass = Class.forName(mappedStatement.getResultTypeStr());
                E entity = (E) entityClass.newInstance();
                Field[] declaredFields = entityClass.getDeclaredFields();

                for (Field field : declaredFields) {
                    // 对成员变量赋值
                    field.setAccessible(true);
                    Class<?> fieldType = field.getType();

                    // 目前只实现了string和int转换
                    if (String.class.equals(fieldType)) {
                        field.set(entity, resultSet.getString(field.getName()));
                    } else if (int.class.equals(fieldType) || Integer.class.equals(fieldType)) {
                        field.set(entity, resultSet.getInt(field.getName()));
                    } else {
                        // 其他类型自己转换，这里就直接设置了
                        field.set(entity, resultSet.getObject(field.getName()));
                    }
                }
                result.add(entity);
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return result;
    }
}
